import axios from "axios";
import { message } from "antd";
import { getToken } from "../utils/user-token";
import { error } from "console";

// axios 创建一个实例，并添加一些默认配置
const instance = axios.create({
  timeout: 100 * 1000,
});

// request 拦截： 接口请求前同一拦截： 统一携带token 固定写法记住即可
instance.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = `Bearer ${getToken()}`;
    return config;
  },
  (error) => Promise.reject(error)
);

// response 拦截：接口返回数据拦截： 统一处理error，msg,没有报错之返回接口中的data字段
instance.interceptors.response.use((res) => {
  const resData = (res.data || {}) as ResType;
  // console.log(resData , '23 ----  axios')
  const { error, data, msg  } = resData;

  if (error !== 0) {
    if (msg) {
      message.error(msg);
    }
    // throw new Error(msg);
  }
  return data as any;
});

export default instance;

// 定义response的返回值类型
export type ResType = {
  error: number;
  data?: ResDataType;
  msg?: string;
};
// data类型，普通对象类型
export type ResDataType = {
  [key: string]: any;
};
